package com.woniuxy.cloud.userassembly.apiImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.woniu.cloud.api.MarketingApi;
import com.woniu.cloud.api.StoreGoodApi;
import com.woniu.cloud.api.serve.ServeApi;
import com.woniu.cloud.common.dto.Result;
import com.woniu.cloud.common.exception.TicketException;
import com.woniu.cloud.common.utils.JWTHelper;
import com.woniu.cloud.entity.SecondService;
import com.woniu.cloud.entity.TStoreGood;
import com.woniuxy.cloud.UserAPI;
import com.woniuxy.cloud.entity.*;
import com.woniuxy.cloud.form.*;
import com.woniuxy.cloud.userassembly.config.RabbitConfig;
import com.woniuxy.cloud.userassembly.service.ITUserCouponService;
import com.woniuxy.cloud.userassembly.service.impl.*;
import com.woniuxy.cloud.userassembly.utils.*;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang.time.DateUtils;
//import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @description:
 * @author: ZXG
 * @time: 2021/9/26
 */
@Slf4j
@GlobalTransactional
@RestController
public class UserApiImpl implements UserAPI {
    @Resource
    private MarketingApi marketingApi;
    @Resource
    private TUserRecordServiceImpl tUserRecordService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private TServiceCarServiceImpl serviceCarService;

    @Resource
    private StoreGoodApi storeGoodApi;

    @Resource
    private TUserServiceImpl tUserService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ITUserCouponService userCouponService;

    @Resource
    private TUserAddressServiceImpl userAddressService;

    @Resource
    private TUserCarServiceImpl userCarService;

    @Resource
    private TGoodCarServiceImpl goodCarService;

    @Resource
    private TUserServiceProcessServiceImpl userServiceProcessService;

    @Resource
    private TUserBlackServiceImpl userBlackService;

    @Resource
    private ServeApi serveApi;
    //测试
    @GetMapping("/test")
    public Object test(){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        return  valueOperations.get("updateMessage17815264993");
    }


    //判断手机号和用户名是否都为空
    public String getPhone(String userName,String  userPhone){
        if(userPhone.isEmpty()){
            if(userName.isEmpty()){
                return null;
            }else{
                //手机号为空查询账户手机号
                TUser user = tUserService.getUserByUserName(userName);
                return user.getUserPhone();
            }
        }
        return userPhone;
    }


    //验证手机号参数
    public Result testPhone(String phone,String userName){
        //判断是电话号码是否存在
        if(phone.isEmpty()){
            if(userName.isEmpty()){
                return Result.fail("请输入手机号或用户名",null);
            }
        }else if(phone.length()!=11){
            return Result.fail("手机号格式错误",null);
        }
        return null;
    }


     //发送短信
     public Result getMessage(String userName,String userPhone,String messageType){
         String phone = getPhone(userName, userPhone);
         if(phone.isEmpty()){
             return Result.fail("请输入手机号或用户名",null);
         }
         //获取随机验证码
         String code= RandomCode.getCode();
         //将验证码存入redis
         ValueOperations valueOperations = redisTemplate.opsForValue();
         String key=messageType+phone;
         //5分钟内不能重复发送
         if(redisTemplate.hasKey(key)){
             return Result.fail("验证码已发送",null);
         }
         //设置验证码为5分钟
         valueOperations.set(key,code,5, TimeUnit.MINUTES);
         //发送短信
//         String message = MessageUtils.getMessage(phone,code);
         return Result.success("执行成功",code);
     }





    /**
     * 查询用户积分
     * @param userId 用户id
     * @return Returns
     */
    @Override
    public Result getScoreByUserId(Integer userId) {
        log.info("用户id={}",userId);
        if(null!=userId) {
            TUser user = tUserService.getUserByUserId(userId);
            if(null==user){
                return  Result.fail("查询失败",null);
            }
            return Result.success("查询成功",user.getUserScore());
        }
        return Result.fail("参数不能为空",null);
    }


    /**
     * 获取修改密码短信
     * @param userName  用户名
     * @param userPhone 手机号
     * @return Result
     */
    @Override
    public Result getUpdateMessage(String userName,String userPhone) {
        log.info("用户名={}，手机号={}",userName,userPhone);
        return getMessage(userName,userPhone,"updateMessage");
    }



    /**
     * 修改密码
     * @param code      验证码
     * @param newPassWord 新密码
     * @return
     */
    @Override
    public Result updatePassWord(@Size(min = 6,max = 6,message = "验证码只能是6位数的数字") String code,@NotBlank(message = "密码不能为空") String newPassWord) {
        log.info("验证码={},密码={}",code,newPassWord);
        if(newPassWord.length()>16||newPassWord.length()<6){
            return Result.fail("密码长度为6-16位",null);
        }
        //密码加密
        newPassWord=EnycrptUtils.enycrpt(newPassWord);
//      Integer userId = Integer.parseInt(request.getHeader("userId"));
        Integer userId =1;
        //redis判断验证码是否过期
        TUser user = tUserService.getUserByUserId(userId);
        if(!redisTemplate.hasKey("updateMessage"+user.getUserPhone())){
          return Result.fail("请发送验证码",null);
        }
        //判断验证码是否正确
        if(!(code.equals(redisTemplate.opsForValue().get("updateMessage"+user.getUserPhone()).toString()))){
           return Result.fail("验证码错误",null);
        }
        //密码不能和原密码一致
        if(user.getUserPassword().equals(newPassWord)){
            return Result.fail("密码和原密码一致",null);
        }
        //修改密码
        if(tUserService.updateUserPassWord(userId, code, newPassWord)!=1){
            return  Result.fail("修改失败",null);
        }
        //修改成功移除redis中的验证码
        redisTemplate.delete("updateMessage"+user.getUserPhone());
        return Result.success("修改成功",null);

    }


    /**
     * 获取登录验证码
     * @param userName  用户名
     * @param userPhone 手机号
     * @return
     */
    @Override
    public Result getLoginMessage(String userName, String userPhone) {
        log.info("用户名={}，手机号={}",userName,userPhone);
        return getMessage(userName,userPhone,"loginMessage");
    }

    /**
     * 手机验证登录
     * @param userPhone 手机号
     * @param code    验证码
     * @return Result
     */
    @Override
    public Result loginByUserPhone(String userPhone, String code) {
        log.info("手机号={},验证码={}",userPhone,code);
        //验证手机号格式
        if(userPhone.length()!=11){
            return Result.fail("手机号格式错误",null);
        }
        //判断验证码是否存在
        if(!redisTemplate.hasKey("loginMessage"+userPhone)){
            return Result.fail("请发送验证码",null);
        }
        //判读验证码是否正确
        if(!code.equals(redisTemplate.opsForValue().get("loginMessage" + userPhone).toString())){
            return Result.fail("验证码错误",null);
        }
        TUser user = tUserService.getUserByUserPhone(userPhone);
        //判断用户是否在黑名单内
        if(userBlackService.getUserBlackByUserId(user.getUserId())!=null){
            return Result.fail("账号已冻结",null);
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("userId",tUserService.getUserByUserPhone(userPhone).getUserId());
        //登录成功
        JWTHelper jwtHelper = new JWTHelper();
        String jwt = jwtHelper.createJWT(DateUtils.addHours(new Date(), 48), stringObjectHashMap);
        response.setHeader("jwt",jwt);
        //登录成功移除redis中的验证码
        redisTemplate.delete("loginMessage"+userPhone);
        return Result.success("登录成功",jwt);
    }


    /**
     * 手机号/账号+密码登录
     * @param userName  用户名
     * @param userPhone 手机号
     * @param passWord  密码
     * @return Result
     */
    @Override
    public Result login(String userName, String userPhone,@NotBlank String passWord) {
        Result result = testPhone(userPhone, userName);
        TUser user=null;
        //手机号用户名验证
        if(result!=null){
           return result;
        }
        user= !userName.isEmpty()?tUserService.getUserByUserName(userName):tUserService.getUserByUserPhone(userPhone);
        if(user==null){
            return Result.fail("账号或密码错误",null);
        }
        if(!user.getUserPassword().equals(EnycrptUtils.enycrpt(passWord))){
            return Result.fail("账号或密码错误",null);
        }
        if(userBlackService.getUserBlackByUserId(user.getUserId())!=null){
            return Result.fail("账号已冻结",null);
        }
        //登录成功
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("userId",user.getUserId());
        JWTHelper jwtHelper = new JWTHelper();
        String jwt = jwtHelper.createJWT(DateUtils.addHours(new Date(), 48), stringObjectHashMap);
        response.setHeader("jwt",jwt);
        return Result.success("登录成功",jwt);
    }


    /**
     * 注销登录
     * @return Result
     */
    @Override
    public Result cancellation() {
        response.setHeader("jwt","");
        return Result.success("注销登录",null);
    }


    /**
     * 获取注册的短信
     * @param userPhone 手机号
     * @return Result
     */
    @Override
    public Result getRegisterMessageByUserPhone(String userPhone) {
        log.info("注册手机号={}",userPhone);
        return getMessage(null,userPhone,"registerMessage");
    }


    /**
     * 查看手机号是否注册
     * @param phone 手机号
     * @return Result
     */
    @Override
    public Result getTestPhone(@NotBlank String phone) {
        log.info("查看手机号={}",phone);
        //判断手机号位数
        if(phone.length()!=11){
            return Result.fail("手机号格式错误",null);
        }
        return  tUserService.getUserByUserPhone(phone)!=null?Result.fail("手机号已注册",null):Result.success("可以使用",null);
    }


    /**
     * 注册
     * @param registerForm
     * @return Result
     */
    @Override
    public Result register(@Validated RegisterForm registerForm) {
        log.info("注册参数={}",registerForm);
        try{
            ValidationUtils.validate(registerForm);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }
        //查询手机号是否已注册
         if(tUserService.getUserByUserPhone(registerForm.getPhone())!=null){
             return  Result.fail("手机号已注册",null);
         }
        //判断用户是否可用
        if(tUserService.getUserByUserName(registerForm.getUserName())!=null){
            return Result.fail("用户名已存在",null);
        }
        if(!redisTemplate.hasKey("registerMessage"+registerForm.getPhone())){
            return Result.fail("请获取验证码",null);
        }
        if(!(Integer.parseInt(redisTemplate.opsForValue().get("registerMessage"+registerForm.getPhone()).toString())==registerForm.getCode())){

            return Result.fail("验证码错误",null);
        }
        //注册成功移除验证码
        redisTemplate.delete("registerMessage"+registerForm.getPhone());
        TUser register = tUserService.register(registerForm);
        return register.getUserId()==null?Result.success("注册成功",register):Result.fail("注册失败",register);
    }

    /**
     * 用户新增优惠劵
     * @param addCouponForm
     * @return Result
     */
    @Override
    public Result insetCouponByUserId(@Validated AddCouponForm addCouponForm) {
        log.info("新增优惠劵参数={}",addCouponForm);

        try{
            ValidationUtils.validate(addCouponForm);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }

        if(tUserService.getUserByUserId(addCouponForm.getUserId())==null){
          return Result.fail("用户不存在,参数异常",null);
        }
        //判断优惠劵是否存在
          if(null==marketingApi.getCouponByConponId(addCouponForm.getCouponId())){
              return Result.fail("优惠劵不存在",null);
          }
        return userCouponService.addUserCoupon(addCouponForm)==1?Result.success("添加成功",null):Result.fail("添加失败",null);
    }



    /**
     * 查看拥有的优惠劵
     * @param userId 用户id
     * @return Result
     */
    @Override
    public Result getCouponsListByUserId(@NotNull Integer userId) {
        if(tUserService.getUserByUserId(userId)==null){
            return Result.fail("用户不存在,参数异常",null);
        }
        return Result.success("执行完成",userCouponService.getUserCouponListByUserId(userId));
    }

    /**
     * 修改优惠劵
     * @param userCouponId
     * @param num
     * @return
     */
    @Override
    public Result updateUserCouponNumByUserCouponId(Integer userCouponId, Integer num) {
        log.info("进入到用户使用了优惠券，减少优惠券数量中,参数 userCouponId = {}, num ={}",userCouponId,num);
        if(userCouponId==null||num==null||userCouponId==0){
            log.info("参数错误");
            throw new TicketException("参数错误");
        }
        Boolean bool = userCouponService.updateUserCouponNumByUserCouponId(userCouponId,num);
        return bool?Result.success("修改成功",bool):Result.fail("修改失败",bool);
    }

    /**
     * 新增用户收货地址
     * @param userAddressForm
     * @return Result
     */
    @Override
    public Result insertAddress(@Validated UserAddressForm userAddressForm) {
          log.info("用户新增地址信息={}",userAddressForm);
        try{
            ValidationUtils.validate(userAddressForm);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }
        return  userAddressService.addUserAddress(userAddressForm)==1?Result.success("新增成功",null):Result.fail("新增失败",null);
    }

    /**
     * 根据用户id查询收货地址
     * @return Result
     */
    @Override
    public Result getAddressByUserId(Integer userId) {
        log.info("用户id={}",userId);
        return  Result.success("执行完成",userAddressService.getUserAddressListByUserId(userId));
    }

    /**
     * 修改用户收货地址
     * @param updateUserAddressForm
     * @return Result
     */
    @Override
    public Result updateAddressByUserAddressId(@Validated UpdateUserAddressForm updateUserAddressForm) {
        log.info("修改用户地址参数={}",updateUserAddressForm);
        try{
            ValidationUtils.validate(updateUserAddressForm);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }
        return userAddressService.updateUserAddress(updateUserAddressForm)==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }

    /**
     * 修改用户默认地址
     * @param userAddressId 用户地址id
     * @return Result
     */
    @Override
    public Result updateDefaultAddress( Integer userAddressId) {
        Integer userId=1;
        log.info("用户id={},用户收货地址id={}",userId,userAddressId);
        if(userAddressService.getUserAddressById(userAddressId)==null){
            return Result.fail("该地址不存在",null);
        }
        if(tUserService.getUserByUserId(userId)==null){
            return Result.fail("用户不存在",null);
        }
        return   tUserService.updateDefaultUserAddressByUserId(userId,userAddressId)==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }

    /**
     * 删除收货地址
     * @param userAddressId 用户地址id
     * @return
     */
    @Override
    public Result deleteAddressByUserAddress(Integer userAddressId) {
        log.info("用户地址={}",userAddressId);
        if(userAddressService.getUserAddressById(userAddressId)==null){
            return Result.fail("该地址不存在",null);
        }
        TUserAddress userAddress = userAddressService.getUserAddressById(userAddressId);
        //查询用户默认地址
        TUser user= tUserService.getUserByUserId(userAddress.getUserAddressUserId());
        //删除用户地址是默认地址则修改
        if(Integer.parseInt(user.getUserDefaultAddress())==userAddressId){
            tUserService.updateDefaultUserAddressByUserId(user.getUserId(),0);
        }
        return userAddressService.deleteUserAddressById(userAddressId)==1?Result.success("删除成功",null):Result.fail("删除失败",null);
    }

    /**
     * 用户新增爱车
     * @param userId
     * @param userCarCarSeriesId
     * @return Result
     */
    @Override
    public Result insertCar(Integer userId,Integer userCarCarSeriesId) {
        AddUserCarForm addUserCarForm = new AddUserCarForm();
        addUserCarForm.setUserId(userId);
        addUserCarForm.setUserCarCarSeriesId(userCarCarSeriesId);
        log.info("新增爱车参数={}", userCarCarSeriesId);
        return userCarService.insertUserCar(addUserCarForm) == 1 ? Result.success("添加成功", null) : Result.fail("添加失败", null);
    }

    /**
     * 用户移除爱车
     * @param userCarId 用户车型id
     * @return Result
     */
    @Override
    public Result deleteCarByUserCarId(Integer userCarId) {
        log.info("用户车型id={}",userCarId);
        return userCarService.deleteUserCar(userCarId)==1?Result.success("移除成功",null):Result.fail("移除失败",null);
    }

    /**
     * 修改用户默认车型
     * @param userCarId 用户车型id
     * @return
     */
    @Override
    public Result updateDefaultCarByUserCarId(Integer userId,Integer userCarId) {

        TUserCar defaultUserCar = userCarService.getDefaultUserCar(userId);
        Integer status =1;
        //设置之前的默认车型状态 0表示默认 1表示不默认
        if (defaultUserCar!=null){
           status= userCarService.updateUserCarStatus(defaultUserCar.getUserCarId(),1);
        }
        return  status==1&&userCarService.updateUserCarStatus(userCarId,0)==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }


    /**
     * 获取用户爱车
     * @param userId
     * @return Result
     */
    @Override
    public Result getUserCarListByUserId(Integer userId) {
        log.info("用户id={}",userId);
        return Result.success("执行完成",userCarService.getUserCarListByUserId(userId));
    }

    /**
     * 获取用户详情
     * @param userId
     * @return Result
     */
    @Override
    public Result getUserByUserId(Integer userId) {
        log.info("用户id={}",userId);
        TUser user= tUserService.getUserByUserId(userId);
        System.err.println(user);
        return null!=user?Result.success("查询成功",user):Result.fail("查询失败",user);
    }



    //发送消息队列
    public void setRabbitMQ(AddUserRecordForm addUserRecordForm){
        rabbitTemplate.convertAndSend(RabbitConfig.RECORD_FINISH_EXCHANGE,
                RabbitConfig.RECORD_FINISH_RK,
                addUserRecordForm
        );
    }

    /**
     * 充值修改余额
     * @param userId
     * @param userBalance 充值余额
     * @return Result
     */
    @Override
    public Result addUserBalanceByUserId(Integer userId,Double userBalance) {
        log.info("用户id={},充值余额={}",userId,userBalance);
        TUser user = tUserService.getUserByUserId(userId);
        if(null==user){
            return Result.fail("用户不存在",null);
        }
        if(tUserService.updateUserbalanceByUserId(userId,userBalance+user.getUserBalance())==1){
            AddUserRecordForm addUserRecordForm = new AddUserRecordForm(userId,userBalance,new Date(),"充值");
            //发送消息队列
            setRabbitMQ(addUserRecordForm);
            return Result.success("充值成功",null);
        }
        return Result.fail("充值失败",null);
        }



    /**
     * 提现
     * @param userId
     * @param userBalance 提现余额
     * @return Result
     */
    @Override
    public Result withdraw(Integer userId,Double userBalance) {
        log.info("用户id={},提现余额={}",userId,userBalance);
        TUser user = tUserService.getUserByUserId(userId);
        if(user.getUserBalance()<userBalance){
           return Result.fail("余额不足",null);
        }
        if(tUserService.updateUserbalanceByUserId(userId,user.getUserBalance()-userBalance)==1){
            AddUserRecordForm addUserRecordForm = new AddUserRecordForm(userId,userBalance,new Date(),"提现");
             //发送消息队列
            setRabbitMQ(addUserRecordForm);
            return Result.success("提现成功",null);

        }else{
            return Result.fail("提现失败",null);
        }

    }







    /**
     * 余额支付
     * @param userId
     * @param  userBalance 修改的余额
     * @return
     */
    @Override
    public Result updateUserBalnceByUserId(Integer userId,Double userBalance) {
        log.info("用户id={},支付余额={}",userId,userBalance);
        TUser user = tUserService.getUserByUserId(userId);
        if(user.getUserBalance()-userBalance<0){
           return Result.fail("余额不足",null);
        }
        //单笔消费过100加10积分
        if(userBalance>=100){
            tUserService.updateUserScoreById(userId,user.getUserScore()+10);
        }
          updateUserPayFeeByUserId(userId,userBalance);
        if(tUserService.updateUserbalanceByUserId(userId,user.getUserBalance()-userBalance)==1){
            AddUserRecordForm addUserRecordForm = new AddUserRecordForm(userId,userBalance,new Date(),"支付");
            //发送消息队列
            setRabbitMQ(addUserRecordForm);
            return Result.success("支付成功",null);
        }else{
            return Result.fail("支付失败",null);
        }
    }



    /**
     * 新增用户消费金额
     * @param userId
     * @param userPayFee 用户消费金额
     * @return Result
     */
    @Override
    public Result updateUserPayFeeByUserId(Integer userId,Double userPayFee){
        log.info("消费金额={}",userPayFee);
        TUser user = tUserService.getUserByUserId(userId);
        return tUserService.updateUserPayFeeByUserId(userId,user.getUserPayFee()+userPayFee)==1?Result.success("增加成功",null):Result.fail("增加失败",null);
    }



    @Value("${oss.host}")
    private String ossHost;
    @Resource
    private OSS ossCli;
    /**
     * 修改用户头像
     * @param userId
     * @param file   上传的图片
     * @return Result
     */
    @Override
    public Result updateUserProfilePhotoByUserId(Integer userId, MultipartFile file) throws IOException {
        //获取用户的id
        TUser user = tUserService.getUserByUserId(userId);
        log.info("用户头像={}",file);
        //文件名加入日期格式
        String format = org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
        String filename = format+file.getOriginalFilename();
        log.info("文件名：{}",filename);
        //文件元数据中存入contentType，便于访问
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(OSSUtils.getContentType(filename));
        //存储
        PutObjectResult uploadResult = ossCli.putObject("woniuxy-zxg", "user/"+user.getUserName()+"/"+filename, file.getInputStream(),meta);
        return tUserService.updateUserImage(userId,ossHost+"user/"+user.getUserName()+"/"+filename)==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }


    /**
     * 修改支付密码
     * @param userPaymentPassWord 旧支付密码
     * @param newPassWord         新支付密码
     * @return Result
     */
    @Override
    public Result updateUserPassWordByUserId( Integer userId,String userPaymentPassWord, String newPassWord) {
         log.info("用户id={},原密码={}，新密码={}",userId,userPaymentPassWord,newPassWord);
        TUser user = tUserService.getUserByUserId(userId);
         if(!user.getUserPaymentPassword().equals(userPaymentPassWord)){
             return Result.fail("原密码错误",null);
         }
        if(user.getUserPaymentPassword().equals(newPassWord)){
            return Result.fail("新密码和原密码不能一致",null);
        }
        return tUserService.updatePayPassword(userId,newPassWord)==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }


    /**
     * 添加用户的积分
     * @param userId
     * @param userScore 修改的积分数
     * @return Result
     */
    @Override
    public Result addUserScoreByUserId(Integer userId,Integer userScore) {
        log.info("用户id={},用户积分={}",userId,userScore);
        TUser user = tUserService.getUserByUserId(userId);
        if(null==user){
            return Result.fail("用户不存在",null);
        }
        return tUserService.updateUserScoreById(userId,user.getUserScore()+userScore)==1?Result.success("添加成功",null):Result.fail("添加失败",null);
    }

    /**
     * 消费积分
     * @param userId
     * @param userScore 修改的积分数
     * @return
     */
    @Override
    public Result reduceUserScoreByUserId(Integer userId,Integer userScore) {
        log.info("用户id={},用户积分={}",userId,userScore);
        TUser user = tUserService.getUserByUserId(userId);
        if(null==user){
            return Result.fail("用户不存在",null);
        }
        //判断积分是否足够
        if(user.getUserScore()<userScore){
            return Result.fail("积分不足",null);
        }
        return tUserService.updateUserScoreById(userId,user.getUserScore()-userScore)==1?Result.success("积分修改成功",null):Result.fail("积分修改失败",null);
    }

    /**
     * 修改用户昵称
     * @param userId
     * @param newName 新昵称
     * @return Result
     */
    @Override
    public Result updateUserNickNameByUserId(Integer userId,String newName) {
        log.info("用户id={},名称={}",userId,newName);
        TUser user = tUserService.getUserByUserId(userId);
        return  tUserService.updateUserNickName(userId,newName)==1?Result.success("昵称修改成功",null):Result.fail("昵称修改失败",null);
    }

    /**
     *  新增购物车
     * @param goodCar
     * @return
     */
    @Override
    public Result insertGoodCar(AddGoodCarForm goodCar){
        Integer userId=1;
        log.info("购物车参数={},用户id={}",goodCar,userId);
        try{
            ValidationUtils.validate(goodCar);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }
        //计算小计
        Result storeGood = storeGoodApi.getStoreGoodByStoreGoodId(goodCar.getGoodCarStoreGoodId());
        log.info("{}",storeGood);
        Object data = storeGood.getData();
        TStoreGood tStoreGood = JSON.parseObject(JSON.toJSONString(data), TStoreGood.class);
        log.info("{}",tStoreGood);
        if(tStoreGood==null){
            return Result.fail("该商品不存在",null);
        }
        if(goodCar.getGoodCarNum()>tStoreGood.getStoreGoodNum()){
            return Result.fail("库存不足",null);
        }
        //查询商品购物车是否存在
        TGoodCar tgoodCar = goodCarService.getGoodCarByUserIdAndGoodId(userId, goodCar.getGoodCarStoreGoodId());
       if(tgoodCar!=null){
           if(goodCar.getGoodCarNum()+tgoodCar.getGoodCarNum()>tStoreGood.getStoreGoodNum()){
               return Result.fail("库存不足",null);
           }
         Integer num=  tgoodCar.getGoodCarNum()+goodCar.getGoodCarNum();
          return  goodCarService.updateGoodCarNumByGoodCarId(tgoodCar.getGoodCarId(),num,num*tStoreGood.getStoreGoodPrice())==1?Result.success("添加成功",null):Result.fail("添加失败",null);
       }

       //不存在新增商品购物车
        TGoodCar tGoodCar = new TGoodCar();
        tGoodCar.setGoodCarNum(goodCar.getGoodCarNum());
        tGoodCar.setGoodCarStoreGoodId(goodCar.getGoodCarStoreGoodId());
        tGoodCar.setGoodCarTotal(tStoreGood.getStoreGoodPrice()*goodCar.getGoodCarNum());
        tGoodCar.setGoodCarUserId(userId);
        return goodCarService.addGoodCar(tGoodCar)==1?Result.success("新增购物车成功",null):Result.fail("新增购物车失败",null);
    }


    /**
     * 删除商品购物车
     * @param goodCarId 购物车id
     * @return
     */
    @Override
    public Result deleteGoodCarByGoodCarId(Integer goodCarId) {
        log.info("购物车id={}",goodCarId);
        return goodCarService.deleteUserGoodCarByGoodCarId(goodCarId)==1?Result.success("删除成功",null):Result.fail("删除失败",null);
    }

    /**
     * 修改商品购物车数量
     * @param goodCarId 购物车id
     * @param goodCarNum 修改的数量
     * @return
     */
    @Override
    public Result updateGoodCarNumByGoodCarId(Integer goodCarId, Integer goodCarNum) {
        log.info("购物车id={},购买数量={}",goodCarId,goodCarNum);
        TGoodCar goodCar = goodCarService.getGoodCarByGoodCarId(goodCarId);
        if(goodCar==null){
            return Result.fail("商品购物车不存在",null);
        }
        goodCarNum+=goodCar.getGoodCarNum();
        if(goodCarNum<1){
            return Result.fail("修改失败",null);
        }
        Result storeGood = storeGoodApi.getStoreGoodByStoreGoodId(goodCar.getGoodCarStoreGoodId());
        log.info("{}",storeGood);
        Object data = storeGood.getData();
        TStoreGood tStoreGood = JSON.parseObject(JSON.toJSONString(data), TStoreGood.class);
        log.info("{}",tStoreGood);
        if(tStoreGood==null){
            return Result.fail("该商品不存在",null);
        }
        if(goodCarNum+tStoreGood.getStoreGoodNum()>tStoreGood.getStoreGoodNum()){
            return Result.fail("库存不足",null);
        }
        return goodCarService.updateGoodCarNumByGoodCarId(goodCarId,goodCarNum,tStoreGood.getStoreGoodPrice()*goodCarNum)==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }


    /**
     * 查询用户所有购物车商品
     * @param userId
     * @return Result
     */
    @Override
    public Result getGoodCarListByUserId(Integer userId) {
        log.info("用户id={}",userId);
        return Result.success("执行完成",goodCarService.getGoodCarListByUserId(userId));
    }


    /**
     * 新增服务购物车
     * @param addServiceCarForm
     * @return Result
     */
    @Override
    public Result insertServiceCar(AddServiceCarForm addServiceCarForm) {
        Integer userId=1;
        log.info("新增服务购物车参数={},用户id={}",addServiceCarForm,userId);
        try{
            ValidationUtils.validate(addServiceCarForm);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }
        //查询二级服务
        Result secondServiceBySercondServiceId = serveApi.getSecondServiceBySercondServiceId(addServiceCarForm.getServiceCarSecondServiceId());
        Object data = secondServiceBySercondServiceId.getData();
        SecondService secondService = JSON.parseObject(JSON.toJSONString(data), SecondService.class);
        if(secondService==null){
            return Result.fail("二级服务不存在",null);
        }
        //查询服务商品是否已存在
        TServiceCar serviceCar = serviceCarService.getServiceCarByUserIdAndServceId(userId, addServiceCarForm.getServiceCarSecondServiceId());
        if(serviceCar!=null){
            return serviceCarService.updateServiceCarNum(serviceCar.getServiceCarId(),serviceCar.getServiceCarNum()+addServiceCarForm.getServiceCarNum(),(serviceCar.getServiceCarNum()+addServiceCarForm.getServiceCarNum())*secondService.getSecondServicePrice().doubleValue())==1?Result.success("添加成功",null):Result.fail("添加失败",null);
        }
        //不存在新增购物车
        TServiceCar tServiceCar = new TServiceCar();
        tServiceCar.setServiceCarSecondServiceId(addServiceCarForm.getServiceCarSecondServiceId());
        tServiceCar.setServiceCarNum(addServiceCarForm.getServiceCarNum());
        tServiceCar.setServiceCarTotal((secondService.getSecondServicePrice().doubleValue()*addServiceCarForm.getServiceCarNum()));
        tServiceCar.setServiceCarUserId(userId);
        return serviceCarService.insertServiceCar(tServiceCar)==1?Result.success("添加成功",null):Result.fail("添加失败",null);
    }


    /**
     * 查询用户服务进度
     * @param orderDetailId 订单详情id
     * @return Result
     */
    @Override
    public Result getUserServiceByUserServiceProcessId(Integer orderDetailId){
       log.info("订单详情id={}",orderDetailId);
        List<TUserServiceProcess> userServiceProcessesList = userServiceProcessService.getUserServiceProcessesList(orderDetailId);
        if(userServiceProcessesList.isEmpty()){
            return Result.fail("该订单不存在",null);
        }
        return Result.success("查询成功",userServiceProcessesList);
    }

    @Override
    public Result getGoodCarByIds(String id) {
        log.info("进入到查询购物车结算清单 参数 ids={}",id);
        List<Integer> ids = JSONObject.parseArray(id, Integer.class);
        if(ids.size()==0){
            log.info("参数异常");
            throw new TicketException("参数异常");
        }
        List<TGoodCar> tGoodCars = goodCarService.getGoodCarByIds(ids);
        return tGoodCars.size()==0?Result.fail("查询失败",false):Result.success("查询成功",tGoodCars);

    }

//    @Override
//    public Result getGoodCarByIds(List<Integer> ids) {
//        log.info("进入到查询购物车结算清单 参数 ids={}",ids);
//        if(ids.size()==0){
//            log.info("参数异常");
//            throw new TicketException("参数异常");
//        }
//        List<TGoodCar> tGoodCars = goodCarService.getGoodCarByIds(ids);
//        return tGoodCars.size()==0?Result.fail("查询失败",false):Result.success("查询成功",tGoodCars);
//    }

    @Override
    public Result getServiceCarByIds(List<Integer> ids) {
        log.info("进入到查询服务购物车结算清单 参数 ids={}",ids);
        if(ids.size()==0){
            log.info("参数异常");
            throw new TicketException("参数异常");
        }
        List<TServiceCar> tGoodCars = serviceCarService.getServiceCarListByIds(ids);
        return tGoodCars.size()==0?Result.fail("查询失败",false):Result.success("查询成功",tGoodCars);
    }


    /**
     * 修改服务进度状态为开始
     * @param userServiceProcessId 服务流程id
     * @return Result
     */
    @Override
    public Result updateUserServiceStartByUserServiceProcessId(Integer userServiceProcessId) {
        log.info("服务流程id={}",userServiceProcessId);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        valueOperations.set("userServiceProcess"+userServiceProcessId,format);
        return userServiceProcessService.updateUserServiceProcessStatus(userServiceProcessId)==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }

    /**
     * 修改服务进度为结束
     * @param userServiceProcessId 服务流程id
     * @return Result
     */
    @Override
    public Result updateUserServiceOverByUserServiceProcessId(Integer userServiceProcessId) throws ParseException {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String s = valueOperations.get("userServiceProcess" + userServiceProcessId).toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time = sdf.parse(s).getTime();
        long overTime = new Date().getTime();
        double date=(double)(overTime - time)/1000/60;
        redisTemplate.delete("userServiceProcess" + userServiceProcessId);
        return  userServiceProcessService.updateUserServiceProcessStatusOver(userServiceProcessId,new Date())==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }

    /**
     * 移除服务购物车
     * @param serviceCarId 服务购物车id
     * @return Result
     */
    @Override
    public Result deleteServiceCarByServiceCarId(Integer serviceCarId) {
        log.info("服务购物车id={}",serviceCarId);
        return serviceCarService.deleteServiceCar(serviceCarId)==1?Result.success("移除成功",null):Result.fail("移除失败",null);
    }

    /**
     * 修改服务购物车服务数量并修改小计
     * @param serviceCarId 服务购物车id
     * @param serviceCarNum 服务购物车数量
     * @return Result
     */
    @Override
    public Result updateServiceCarNumByServiceCarId(Integer serviceCarId, Integer serviceCarNum) {
        log.info("服务购物车id={},修改的服务数量={}",serviceCarId,serviceCarNum);
        //查看服务购物车数量
        TServiceCar serviceCar = serviceCarService.getServiceCarByServiceCarId(serviceCarId);
        Integer num = serviceCar.getServiceCarNum();
        if(num+serviceCarNum<1){
            return Result.fail("修改失败",null);
        }
        //查询二级服务
        Result secondServiceBySercondServiceId = serveApi.getSecondServiceBySercondServiceId(serviceCar.getServiceCarSecondServiceId());
        Object data = secondServiceBySercondServiceId.getData();
        SecondService secondService = JSON.parseObject(JSON.toJSONString(data), SecondService.class);
        if(secondService==null){
            return Result.fail("二级服务不存在",null);
        }
        return  serviceCarService.updateServiceCarNum(serviceCarId,serviceCarNum+num,(serviceCarNum+num)*secondService.getSecondServicePrice().doubleValue())==1?Result.success("修改成功",null):Result.fail("修改失败",null);
    }

    /**
     * 查询用户的服务购物车列表
     * @param userId
     * @return Result
     */
    @Override
    public Result getServiceCarListByUserId(Integer userId) {
        log.info("用户id={}",userId);
        return Result.success("执行成功",serviceCarService.getServiceCarList(userId));
    }

    /**
     * 新增用户服务流程
     * @param addUserServiceProcessForm
     * @return Result
     */
    @Override
    public Result createUserServiceProcess(AddUserServiceProcessForm addUserServiceProcessForm) {
        log.info("新增用户服务参数={}",addUserServiceProcessForm);
        try{
            ValidationUtils.validate(addUserServiceProcessForm);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }
        return  userServiceProcessService.insertUserServiceProcess(addUserServiceProcessForm)==1?Result.success("新增成功",null):Result.fail("新增失败",null);
    }




    /**
     * 冻结账号
     * @param addUserBlackForm
     * @return
     */
    @Override
    public Result insertUserBlack(AddUserBlackForm addUserBlackForm) {
        log.info("冻结账号参数={}",addUserBlackForm);
        try{
            ValidationUtils.validate(addUserBlackForm);
        }catch(TicketArgsException e){
            return Result.fail(e.getMessage(),null);
        }
       return userBlackService.addUserBlack(addUserBlackForm)==1?Result.success("新增成功",null):Result.fail("新增失败",null);
    }

    @Override
    public Result getUserCouponById(Integer id) {
        TUserCoupon tUserCoupon = userCouponService.getUserCouponById(id);
        return Result.success("查询成功",tUserCoupon);
    }


    @RabbitListener(queues = "queue.record.finish")
    public void  addCredit(AddUserRecordForm addUserRecordForm) {
        log.info("用户操作记录参数={}",addUserRecordForm);
        tUserRecordService.insertUserRecord(addUserRecordForm);
    }


}
